import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<PayTeacherState> buildEffect() {
  return combineEffects(<Object, Effect<PayTeacherState>>{
    Lifecycle.initState: _onInit,
    Lifecycle.dispose: _onDispose,
    PayTeacherAction.onPay: _onPay,
  });
}

void _onInit(Action action, Context<PayTeacherState> ctx) async {
  Future.delayed(Duration.zero, () async {
    _initNewPurchase(ctx);
  });
}

void _onDispose(Action action, Context<PayTeacherState> ctx) async {
  _payProgress = null;
  await FlutterInappPurchase.instance.endConnection;
}

ProgressDialog _payProgress;

void _onPay(Action action, Context<PayTeacherState> ctx) async {
  String productId = action.payload;
  print('>>>> PAY $productId');
  if (productId.isEmpty) {
    return;
  }

  var product = ctx.state.products.firstWhere((p) => p.productId == productId);
  print('>>>> PAY $product');
  _payProgress = new ProgressDialog(ctx.context)..setMessage('正在支付...');
  _payProgress.show();
  FlutterInappPurchase.instance.requestPurchase(productId);
}

/// purchase

Future<void> _initNewPurchase(Context<PayTeacherState> ctx) async {
  var ret = await FlutterInappPurchase.instance.initConnection;
  if (ret == 'false') {
    // ctx.dispatch(PayTeacherActionCreator.button('初始化失败'));
    await Util.showMsgDialog('失败', '初始化失败，请稍后重试', ctx.context);
    Navigator.of(ctx.context).pop('refresh');
    return false;
  }

  // Get list of products
  ctx.state.products =
      await FlutterInappPurchase.instance.getProducts(ctx.state.kProductIds);
  print('>>>> PRODUCTS: ${ctx.state.products}');
  if (ctx.state.products == null || ctx.state.products.isEmpty) {
    // ctx.dispatch(PayListActionCreator.button('获取会员列表失败'));
    await Util.showMsgDialog('失败', '获取会员支付列表失败，请稍后重试', ctx.context);
    Navigator.of(ctx.context).pop('refresh');
    return false;
  }

  // 处理订单
  ctx.state.purchaseUpdatedSub =
      FlutterInappPurchase.purchaseUpdated.listen((productItem) async {
    print('>>>> UPD: $productItem');
    _payProgress?.hide();
    if (productItem == null) {
      return;
    }

    // 验证订单
    bool ok = await Util.verifyPurchase(
        ctx.context, productItem, productItem.productId);
    Navigator.of(ctx.context).pop('refresh');
  });

  // 处理订单错误
  ctx.state.purchaseErrorSub =
      FlutterInappPurchase.purchaseError.listen((purchaseError) {
    print('>>>> ERR: $purchaseError');
    _payProgress?.hide();
    switch (purchaseError.code) {
      case 'E_USER_CANCELLED':
        Util.alert('用户取消交易', ctx.context);
        break;
      case 'E_UNKNOWN':
        Util.alert('未知交易错误', ctx.context);
        break;
      default:
        Util.alert('未知的交易错误', ctx.context);
        print('>>>> ERR: FAIL DEFAULT');
        break;
    }
  });

  // 处理支付但未关闭的订单
  List<PurchasedItem> purchases =
      await FlutterInappPurchase.instance.getAvailablePurchases();
  print('>>>> AVAI: $purchases');
  purchases.forEach((purchase) async {
    // 验证订单
    bool ok = await Util.verifyPurchase(ctx.context, purchase, '');
    Navigator.of(ctx.context).pop('refresh');
  });

  // history
  List<PurchasedItem> pastPurchases =
      await FlutterInappPurchase.instance.getPurchaseHistory();
  print('>>>> HIST: $pastPurchases');

  if (ctx.state.userInfo.containsKey('accountInfo') &&
      (ctx.state.userInfo['accountInfo']['validRechargeUser'] ||
          ctx.state.userInfo['accountInfo']['validBillingCardUser'])) {
    // is member
    ctx.dispatch(PayTeacherActionCreator.button('立即续费'));
  } else {
    ctx.dispatch(PayTeacherActionCreator.button('立即开通'));
  }
}
